import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Table} from 'antd';
import routes from './routes';
import Return from '../common/Return';
import {FORM_OPTIONS, FIXED_COLUMN_WIDTH, TABLE} from '../constants';
import {getMaintainDetail} from './api';
import ProductCategoryListPanel from './ProductCategoryListPanel';
import {baseDataStatus} from '../Enum';
import {conventEnumValueToString} from '../utils';
import SearchInput from 'Shared/components/SearchInput';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
const FormItem = Form.Item;

export class MaintainPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: {},
        productCategoryDetails: [],
        showProductCategoryListPanel: false,
    }
   
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getMaintainDetail(id)
            .then(res => {
                if(res.ok) {
                    res.data.needTransportScanning = res.data.needTransportScanning ? 1 : 0;
                    res.data.isOffsiteFactory = res.data.isOffsiteFactory ? 1 : 0;
                    this.setState({
                        loading: false,
                        data: res.data,
                        productCategoryDetails: res.data.productCategories
                    });
                } else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onClickAddBtn = () => {
        this.setState({showProductCategoryListPanel: true});
    }
    onCloseProductCategoryPanel = () => {
        this.setState({showProductCategoryListPanel: false});
    }

    onSelectProductCategory = records => {
        const addedItems = this.state.productCategoryDetails || [];
        records.forEach(r => {
            const index = addedItems.findIndex(v => v.id === r.id);
            if(index === -1)
                addedItems.push({
                    id: r.id,
                    code: r.code,
                    name: r.name,
                });
        });
        this.setState({
            productCategoryDetails: [...addedItems],
            hasOperat: true,
            showProductCategoryListPanel: false
        });
    }
    onSelectSubClaim = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                manufacturerId: records.id,
                code: records.manufacturerCode,
                name: records.manufacturerName,
                areaName: records.areaName,
                needTransportScanning: records.needTransportScanning,
                isOffsiteFactory: records.isOffsiteFactory,
                status: records.status,
                remark: records.remark
            }),
            hasOperat: true,
            showManufacturer: false
        });
    }
    onSelectParts = (productCategoryId, value) => {
        const materials = this.state.productCategoryDetails;
        const tmp = materials.map(item => {
            if(item.productCategoryId === productCategoryId)
                return Object.assign({}, item, {
                    productCategoryId: value.id,
                    productCategoryCode: value.code,
                    productCategoryName: value.name
                });
            return item;
        });
        this.setState({
            productCategoryDetails: tmp,
            hasOperat: true
        });
    };
    onPersonnelDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.productCategoryDetails.filter(d => d.id !== addedItemId);
        this.setState({
            productCategoryDetails: [...tmp],
            hasOperat: true
        });
    }
    onPersonnelDeleteAll = () => {
        this.setState({
            productCategoryDetails: [],
            hasOperat: true
        });
    }

    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onSubmit = () => {
        this.setState({
            loading: true
        });
        const data = this.state.data;
        const productCategoryDetails = this.state.productCategoryDetails;
        this.props.onSubmit(data, productCategoryDetails)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    render() {
        const {data, productCategoryDetails} = this.state;
        const {formatMessage} = this.props.intl;
        const Yes = formatMessage({
            id: 'receivePanel.yes',
            defaultMessage: '是'
        });

        const No = formatMessage({
            id: 'receivePanel.no',
            defaultMessage: '否'
        });
        const columns = [
            {
                title: formatMessage({
                    id: 'productCategoryDetailPanel.productCategoryCode',
                    defaultMessage: '车型编号'
                }),
                dataIndex: 'code',
            },
            {
                title: formatMessage({
                    id: 'productCategoryDetailPanel.productCategoryName',
                    defaultMessage: '车型名称'
                }),
                dataIndex: 'name'
            },
            {
                title: (
                    <WrappedPopconfirm
                        id="maintainPanel.personnel.delete"
                        title={this.props.intl.formatMessage({
                            id: 'maintainPanel.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'maintainPanel.personnel.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'maintainPanel.personnel.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onPersonnelDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'maintainPanel.personnel.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => (
                    <a onClick={this.onPersonnelDeleteAddedItem} data-id={record.id}>
                        {this.props.intl.formatMessage({
                            id: 'maintainPanel.personnel.delete',
                            defaultMessage: '删除'
                        })}
                    </a>
                )
            }
        ];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'maintainPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {this.props.id ? (
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'maintainPanel.form.manufacturer',
                                                defaultMessage: '生产工厂'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <span className="value-font">({data.code}) {data.name}</span>
                                        </FormItem>
                                    </Col>
                                )
                                    : (
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'maintainPanel.operation.manufacturer',
                                                defaultMessage: '生产工厂'
                                            })} {...FORM_OPTIONS.item}>
                                                <SearchInput
                                                    disabled={true}
                                                    value={`${data.code || ''}${data.name || ''}`}
                                                    id={data.id}
                                                    onClickSearchBtn={this.onClickManufacturer} />
                                            </FormItem>
                                        </Col>
                                    )
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'maintainPanel.operation.areaName',
                                        defaultMessage: '省市区县'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.areaName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'maintainPanel.operation.needTransportScanning',
                                        defaultMessage: '是否驳运扫描'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.needTransportScanning ? Yes : No}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'maintainPanel.operation.isOffsiteFactory',
                                        defaultMessage: '是否异地工厂'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.isOffsiteFactory ? Yes : No}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'maintainPanel.operation.status',
                                        defaultMessage: '状态'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(baseDataStatus, data.status)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'maintainPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'maintainPanel.operation.productCategory',
                                defaultMessage: '产品分类清单'
                            })}
                            extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickAddBtn}>
                                    {formatMessage({
                                        id: 'maintainPanel.operation.newDetail',
                                        defaultMessage: '新增'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.productCategoryDetails}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'maintainPanel.btn.submit',
                                        defaultMessage: '提交'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                    {
                        this.state.showProductCategoryListPanel &&
                        <ProductCategoryListPanel
                            selectKey={data.id}
                            onCancel={this.onCloseProductCategoryPanel}
                            onSelect={this.onSelectProductCategory} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

MaintainPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {injectIntl} from './intl';
import {tableSearch, onMaintain} from './actions';

const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, productCategoryDetails) => dispatch(onMaintain(data, productCategoryDetails)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(null, mapDispatchToProps)(injectIntl(MaintainPanel));
